#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/7/3
# @Author  : LiJun
# @Email   : lijun@tianyancha.com
# @Version : 1.0.0
import subprocess


def start_server(port, bport, chrome_port, device):
    cmd = f"appium --session-override --relaxed-security --local-timezone -p {port} -bp {bport} --chromedriver-port {chrome_port} " \
          f"-U {device}"
    appium = subprocess.Popen(
        cmd,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        bufsize=1,
        close_fds=True,
    )
    print("执行启动命令：{}".format(cmd))
    count = 0
    while True:
        appium_line = appium.stdout.readline().strip().decode()
        if "listener started" in appium_line or "Error: listen" in appium_line:
            print("----server_ 成功---")
            break

        count += 1
        if count > 25:
            print("启动等待时间过长")
            raise ValueError("----server_ 端口被占用，启动失败---")
